import { observable, action , toJS} from 'mobx';
import { WeaForm } from 'comsMobx';
import { WeaTableNew } from 'comsMobx';
import {WeaLogView} from 'comsMobx'
import {WeaLocaleProvider} from 'ecCom';
import { Modal , message } from 'antd';
import cloneDeep from 'lodash/cloneDeep';
import * as TEMPLATE_API from '../apis/freeFlowTemplate';

const {LogStore} = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;

export class WFFreeFlowTemplateStore{
    /** 列表store */
    @observable loading = false;
    title ="";
    @observable tableStore = new TableStore();
    @observable logStore = new LogStore();
    @observable logArray = [];
    @observable logModalShow = false;
    /** 列表高级查询store */
    @observable listForm = new WeaForm();
    @observable showSearchAd = false;
    listCondition = [];

    /** 顶部Tab组件store */
    topTab = [];
    @observable topTabCount = {};

    /** 添加、编辑模板 */
    @observable addModalShow = false;
    addCondition = [];
    addForm = new WeaForm();

    @observable editTemplateTabs = [];
    @observable personalTabs = [];
    @observable editModalShow = false;
    @observable editSelectedTabKey = '0';
    @observable curTemplateId = '';
    
    /** 共享范围 */
    shareRangeConfigs = {};
    @observable shareRangeTableStore = new TableStore();
    @observable addShareModalShow = false;
    @observable addShareRef = '';

    /** 模板设置 */
    @observable modelSetModalShow = false;
    @observable curModelObject = {
        name : '',
        namespan : '',
        type : '',
        typespan :''
    };
    @observable modelSetCloseCb = null;

    /** 控制操作按钮状态 */
    @observable operateBtnsState = {
        addSaving : false
    }


    constructor() {
        this.title = getLabel(504067,'流转模板');
    }

    @action
    setLoading(bool = false){
        this.loading = bool;
    }
    @action
    setShowSearchAd = (bool) => {
        this.showSearchAd = bool;
    }
    @action
    getAddTemplateBaseData = () => {
        TEMPLATE_API.getAddTemplateBaseData().then((result)=>{
            console.log(result,'----');
            const { advanceCondition = {} , addTemplateTabs = [], templateBaseInfo = [], addShareForm = {} } = result;
            this.shareRangeConfigs = addShareForm;
            this.editTemplateTabs =  addTemplateTabs;
            this.personalTabs = [addTemplateTabs[0]];
            this.addCondition = [{
                items:templateBaseInfo
            }];
            
            this.listCondition = [advanceCondition];
            this.listForm.setCondition(toJS([advanceCondition]));
            this.listForm.initFormFields([advanceCondition]);
        })
    }
    @action
    searchList = (params = {}) => {
        const listFormParams = this.listForm.getFormParams();
        let searchParams = {...params,...listFormParams};
        let current = this.tableStore.current || 1;
        TEMPLATE_API.getFlowTemplateList(searchParams).then((result)=>{
            const { sessionkey = ''} = result;
            this.tableStore.getDatas(sessionkey, current, "");
        })
    }
    /** add - edit */
    @action
    setAddModalShow = (bool,goDetailSet=false) => {
        this.addModalShow = bool;
        if(bool){
            let condition = this.addCondition[0].items.map(v=>{
                if(v.domkey[0] == 'name'){
                    v.rules = 'required|stringLength:100';
                    v.stringLength = 100;
                }
            })
            this.addForm.setCondition(this.addCondition);
            this.addForm.initFormFields(this.addCondition);
        }else{
            !goDetailSet && this.addForm.resetConditionValue();
        }
    }
    @action
    switchEditTab = (key) => {
        this.editSelectedTabKey = key;
        if(key === '1'){//共享范围
            this.getShareRangeList();
        }
    }
    @action
    setEditModalShow = (bool,item) => {
        this.editModalShow = bool;
        if(!bool){
            this.clearMobxState();
        }
        if(item && bool){
            const { id='',name='',namespan='',type='',typespan=''} = item[0];
            const condition = cloneDeep(toJS(this.addCondition));
            condition[0].items[1].viewAttr = 1;
            this.setCurrentModalInfo({name,type});
            this.addForm.setCondition(condition);
            this.addForm.updateFields({name,type},false);
        }
    }
    @action
    addSave = (goDetailSet = false,fromEdit = false) => {
        this.operateBtnsState = {...this.operateBtnsState,addSaving:true}

        message.loading(getLabel(129514,'正在保存数据，请稍候...'),0);
        const addParams = this.addForm.getFormParams();
        if(fromEdit){
            addParams['templateid'] = this.curTemplateId;
        }
        TEMPLATE_API.saveFlowTemplate(addParams).then((result)=>{
            const { success = false , id = '',isRepeat = false} = result;
            this.operateBtnsState = {...this.operateBtnsState,addSaving:false}
            if(success){
                message.destroy();
                message.success(getLabel(83551,'保存成功！'));
                this.searchList();
                !fromEdit && this.setAddModalShow(false,goDetailSet);
                fromEdit && this.setEditModalShow(false);
                if(goDetailSet){
                    this.curTemplateId = id;
                    this.setCurrentModalInfo(addParams);
                    this.setEditModalShow(true,[{name:addParams.name,type:addParams.type}]);
                }
            }else{
                message.destroy();
                if(isRepeat) {
                    message.warning(getLabel(386286,'"名称"已存在，请重新输入！'));
                } else {
                    message.error(getLabel(84544,'保存失败！'));
                }
            }
        });
        
    }
    @action
    deleteTemplateItem = (ids='',isBatch=false) => {
        const _this = this;
        let deleteParams = {
            delids:ids
        };
        Modal.confirm({
            title:getLabel(131329,' 信息确认'),
            content: isBatch ? getLabel(33435,'确定要删除选中的记录吗？') : getLabel(129890,'确定要删除吗?'),
            onOk() {
                message.loading(getLabel(84024,'正在删除数据，请稍候...'),0);
                TEMPLATE_API.deleteTemplate(deleteParams).then((result)=>{
                    const { success = false , rightDelIds = ''} = result;
                    _this.searchList();
                    if(rightDelIds != ''){
                        message.destroy();
                        message.success(getLabel(83472,'删除成功！'));
                    }else{
                        message.destroy();
                        message.error(getLabel(83473,'删除失败！'));
                    }
                    console.log(result,'result')
                })
            },
            onCancel() {},
            okText:getLabel(83446,'确定'),
            cancelText:getLabel(31129,'取消')
        });
    }
    @action
    setLogModalShow = (bool) => {
        this.logModalShow = bool;
    }
    /***********/
    /** 共享范围 */
    @action
    getShareRangeList = () => {
        let queryParams = {templateid:this.curTemplateId};
        let current = this.shareRangeTableStore.current || 1;
        TEMPLATE_API.getTemplateShareList(queryParams).then((result)=>{
            const { sessionkey = ''} = result;
            this.shareRangeTableStore.getDatas(sessionkey, current, "");
        });
    }
    @action
    setAddShareModalShow = (bool) => {
        this.addShareModalShow = bool;
    }
    @action
    saveAddedShare = (params={}) => {
        console.log(params,'save share');
        /**
        templateid	模板ID
        sharetype	共享类型
        shareobj	共享对象ID串
        bhxj	是否包含下级
        sharelevel	共享级别
        sharelevelobj	共享级别对象 主要是角色
        seclevel	安全级别最小值
        seclevelmax 安全级别最大值
        */
        let saveParams = {
            templateid:this.curTemplateId,
            sharetype:'',
            bhxj:'',
            sharelevel:'',
            sharelevelobj:'',
            seclevel:'',
            seclevelmax:'255'
        };
        saveParams = {...saveParams,...params};
        if(saveParams.seclevel * 1> saveParams.seclevelmax){
            message.destroy();
            message.warning(getLabel(385085,"安全级别设置有误，请重新设置"));
        }else{
            message.loading(getLabel(129514,'正在保存数据，请稍候...'),0);
            TEMPLATE_API.saveTemplateShare(saveParams).then((result)=>{
                const { success = false } = result;
                if(success){
                    message.destroy();
                    message.success(getLabel(83551,'保存成功！'));
                    this.getShareRangeList();
                    this.setAddShareModalShow(false);
                }else{
                    message.destroy();
                    message.error(getLabel(84544,'保存失败！'));
                }
                console.log(result,'result')
            })
        }
    }
    @action
    deleteShareItem = (ids='') => {
        let deleteParams = {
            templateid:this.curTemplateId,
            delids:ids
        };
        const _this = this;
        Modal.confirm({
            title:getLabel(131329,' 信息确认'),
            content: ids.indexOf(',') > -1 ? getLabel(33435,'确定要删除选中的记录吗？') : getLabel(129890,'确定要删除吗?'),
            onOk() {
                message.loading(getLabel(84024,'正在删除数据，请稍候...'),0);
                TEMPLATE_API.deleteTemplateShare(deleteParams).then((result)=>{
                    const { success = false , hasDelRight} = result;
                    console.log(result,'result');
                    if(success){
                        message.destroy();
                        message.success(getLabel(83472,'删除成功！'));
                        _this.getShareRangeList();
                    }else{
                        message.destroy();
                        message.error(getLabel(83473,'删除失败！'));
                    }
                })
            },
            onCancel() {},
            okText:getLabel(83446,'确定'),
            cancelText:getLabel(31129,'取消')
        });
        
    }
    @action
    clearMobxState = () => {
        this.editSelectedTabKey = '0';
        this.addForm.resetConditionValue();
    }
    /********/
    /** 模板设置 */
    @action
    setModelSetModalShow = (bool) => {
        this.modelSetModalShow = bool;
    }
    @action
    setCurrentModalInfo = (params = {}) => {
        this.curModelObject = {...this.curModelObject,...params};
    }
    /********/
    @action
    appendListFormFields = (value) => {
        this.listForm.updateFields(value, false);
    }
    @action
    clearListFormFields = () => {
        this.listForm.resetConditionValue();      //清除查询条件值
    }

    @action
    clearStatus = () =>{
        this.showSearchAd = false;
        this.clearListFormFields();
        this.tableStore = new TableStore();
        this.title = getLabel(504067,'流转模板');
    }
}